package com.ThreadandAsyn;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;

import com.examplee.username.httpfrist_01.R;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class ListviewActivity extends AppCompatActivity {
private ListView listView;
    private static String Url="http://www.imooc.com/api/teacher?type=4&num=30";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_listview);
        listView= (ListView) findViewById(R.id.imagelistview);
        new Newaysn().execute(Url );
    }
//    实现网络的异步访问
    class Newaysn extends AsyncTask<String,Void,List<NewBean>>{


        @Override
        protected List<NewBean> doInBackground(String... params) {

            return getJsonData(params[0]);
        }

    @Override
    protected void onPostExecute(List<NewBean> newBeens) {
        super.onPostExecute(newBeens);
        NewAdapter adapter=new NewAdapter(newBeens,ListviewActivity.this);
        listView.setAdapter(adapter);
    }
}
//将url对应的json数据转化为我们封装的newban对象
    private List<NewBean> getJsonData(String  url) {
        List<NewBean> newbeanlist=new ArrayList<>();
        try {
            String jsonstring=readStream(new URL(url).openStream());
//            Log.d("TAB",jsonstring);
            JSONObject jsonobject;
            NewBean newbean;
            jsonobject=new JSONObject(jsonstring);
            JSONArray jsarray=jsonobject.getJSONArray("data");
            for (int i=0; i<jsarray.length();i++){
                jsonobject=jsarray.getJSONObject(i);
                newbean=new NewBean();
                newbean.newsIconUrl=jsonobject.getString("picSmall");
                newbean.newsContent=jsonobject.getString("description");
                newbean.newsTitle=jsonobject.getString("name");
                newbeanlist.add(newbean);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return newbeanlist;
    }
//    通过inputstream解析网页返回的数组
    private String readStream(InputStream is){
        InputStreamReader reader;
        String result="";
        try {
            String line="";
            reader=new InputStreamReader(is,"utf-8");
            BufferedReader br=new BufferedReader(reader);
            while ((line=br.readLine())!=null){
                result+=line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}

